<template>
  <el-dialog 
    v-model="dialogVisible" 
    :title="mode === 'add' ? '新增产品' : '编辑产品'" 
    width="500"
  >
    <el-form :model="form" label-width="80px" :rules="rules" ref="formRef">
      <el-form-item label="产品名称" prop="name">
        <el-input v-model="form.name" />
      </el-form-item>
      
      <el-form-item label="分类" prop="category">
        <el-select v-model="form.category">
          <el-option
            v-for="item in categories"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="价格" prop="price">
        <el-input-number 
          v-model="form.price" 
          :min="0" 
          :precision="2" 
          style="width: 100%"
        />
      </el-form-item>

      <el-form-item label="库存" prop="stock">
        <el-input-number v-model="form.stock" :min="0" style="width: 100%" />
      </el-form-item>

      <el-form-item label="状态" prop="status">
        <el-switch
          v-model="form.status"
          :active-value="1"
          :inactive-value="0"
        />
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button @click="dialogVisible = false">取消</el-button>
      <el-button type="primary" @click="submitForm">确定</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, watch } from 'vue'
import { ElMessage } from 'element-plus'

const props = defineProps({
  modelValue: Boolean,
  currentProduct: Object,
  mode: String
})

const emit = defineEmits(['update:modelValue', 'submit'])

const categories = [
  { value: '电子产品', label: '电子产品' },
  { value: '办公用品', label: '办公用品' },
  { value: '日用品', label: '日用品' },
  { value: '食品饮料', label: '食品饮料' }
]

const form = ref({
  name: '',
  category: '',
  price: 0,
  stock: 0,
  status: 1
})

const rules = {
  name: [{ required: true, message: '请输入产品名称', trigger: 'blur' }],
  category: [{ required: true, message: '请选择分类', trigger: 'change' }],
  price: [{ required: true, message: '请输入价格', trigger: 'blur' }],
  stock: [{ required: true, message: '请输入库存', trigger: 'blur' }]
}

const formRef = ref(null)
const dialogVisible = ref(false)

watch(() => props.modelValue, (val) => {
  dialogVisible.value = val
})

watch(dialogVisible, (val) => {
  emit('update:modelValue', val)
  if (!val) {
    formRef.value?.resetFields()
  }
})

watch(() => props.currentProduct, (val) => {
  if (val) {
    form.value = { ...val }
  } else {
    form.value = {
      name: '',
      category: '',
      price: 0,
      stock: 0,
      status: 1
    }
  }
})

const submitForm = async () => {
  try {
    await formRef.value.validate()
    emit('submit', { ...form.value })
    dialogVisible.value = false
  } catch (error) {
    ElMessage.warning('请正确填写表单')
  }
}
</script> 